# $Id: scheduler.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

import urllib2
from xml.dom import minidom

from django.conf import settings
from djanet.lib import crontab, log
from djanet.lib.exception import AppError
from djanet.tools.lib import backup, tree

def build_tree():
   if hasattr(settings, 'ASN_URL') and (len(tree.ASNList) == 0):
      try:
         urldata = urllib2.urlopen(settings.ASN_URL)
      except URLError, message:
         pass
      else:
         dom = minidom.parseString(urldata.read())
         for node in dom.getElementsByTagName('record'):
            server = None
            info = None
            asn = node.getElementsByTagName('number')[0].firstChild.nodeValue
            whois = node.getElementsByTagName('whois')
            if whois:
               server = whois[0].firstChild.nodeValue

            desc = node.getElementsByTagName('description')
            if desc:
               info = desc[0].firstChild.nodeValue

            tree.ASNList.append(tree.ASNTree(asn, server, info))

   if hasattr(settings, 'IP_URL') and (len(tree.IPv4List) == 0):
      try:
         urldata = urllib2.urlopen(settings.IP_URL)
      except URLError, message:
         pass
      else:
         dom = minidom.parseString(urldata.read())
         for node in dom.getElementsByTagName('record'):
            server = None
            ipnet = node.getElementsByTagName('prefix')[0].firstChild.nodeValue
            whois = node.getElementsByTagName('whois')
            if whois:
               server = whois[0].firstChild.nodeValue

            tree.IPv4List.append(tree.IPv4Tree(ipnet, server))

def netbackups():
   retval = backup.configbackups()

def run():
   cron = crontab.crond(
         crontab.Event(build_tree, 0, range(0, 24, 4))
         crontab.Event(netbackups, 0, range(0, 24, 6))
         )
   
   cron.daemon = True
   cron.start()
